package com.jar.exercise.设计模式.代理.cglib动态代理;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 实现cglib的动态代理
 */
public class ProxyFactory implements MethodInterceptor {
	private Object target;

	public ProxyFactory() {
	}

	public <T> T newProxyInstance(T target) {
		this.target = target;
		//1、工具类
		Enhancer enhancer = new Enhancer();
		//2、设置父类
		enhancer.setSuperclass(target.getClass());
		//3、设置回调函数
		enhancer.setCallback(this);
		//4、创建代理类
		return (T) enhancer.create();
	}

	/**
	 * 调用目标对象的方法
	 */
	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws InvocationTargetException, IllegalAccessException {
		System.out.println("cglibe代理开始");
		Object invoke = method.invoke(target, objects);
		System.out.println("cglibe代理结束");
		return invoke;

	}

	public static void main(String[] args) {
		TeacherDao teacherDao = new TeacherDao();
		ProxyFactory proxyFactory = new ProxyFactory();
		TeacherDao teacherDao1 = proxyFactory.newProxyInstance(teacherDao);
		teacherDao1.say1();
	}
}

class TeacherDao {
	public void say() {
		System.out.println("老师在教学");
	}

	public void say1() {
		System.out.println("老师在教学");
	}
}
